﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Linq;
using System.IO;
using SpiderPlatform.Entity;

namespace SpiderPlatform.Service
{
    public class RanchService
    {
        string apiService = "https://api.freshop.com/1/products?app_key=99_ranch_market";
        int store_id = 3122;
        string token = "";
        string app_key = "99_ranch_market";
        // string fields = "id,identifier,reference_id,reference_ids,upc,name,store_id,department_id,size,cover_image,price,sale_price,sale_start_date,sale_finish_date,price_disclaimer,sale_price_disclaimer,is_favorite,relevance,popularity,shopper_walkpath,fulfillment_walkpath,quantity_step,quantity_minimum,quantity_initial,quantity_label,quantity_label_singular,varieties,quantity_size_ratio_description,status,status_id,sale_configuration_type_id,fulfillment_type_id,fulfillment_type_ids,other_attributes,clippable_offer,slot_message,call_out,has_featured_offer,tax_class_label,promotion_text,sale_offer,store_card_required,average_rating,review_count,offered_together,sequence";
        string fields = "id,upc,name,store_id,department_id,size,price,sale_price,description,identifier";


    
        public void doWork(bool IsOnlyMail = false)
        {           
            token = GetToken();
            Logger.Info("get token success...");
            var categoryList = GetCategory();
            var totalCate = categoryList.departments[0];
            var cate1 = categoryList.departments.Where(p => p.parent_id == totalCate.id);
            List<RanchProduct> all = new List<RanchProduct>();
            List<RanchDetailEntity> detailList = new List<RanchDetailEntity>();
            DownData(categoryList, cate1, out all, out detailList);
            ImportData(detailList);
            Logger.Info("数据导入完成");

        }
        private string GetToken()
        {
            RanchToken token = new RanchToken();
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://api.freshop.com/2/sessions/8ee2afde191e8b8405d205ba99ff9ab4?app_key={app_key}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                token = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchToken>(data);
            }
            return token.token;

        }
        private void DownData(RanchCategoryResult categoryList, IEnumerable<RanchCategory> cate1, out List<RanchProduct> all, out List<RanchDetailEntity> detailList)
        {            
            all = new List<RanchProduct>();
            detailList = new List<RanchDetailEntity>();

            int skip = 0;
            int page_size = 100;
            RanchProductResult res = new RanchProductResult();
            List<RanchProduct> list = new List<RanchProduct>();
            do
            {
                res = GetProductList(skip, page_size, fields);
                if (res.items?.Count() > 0)
                {
                    list.AddRange(res.items);
                }
                skip += page_size;
            }
            while (res.items?.Count() > 0);
            all.AddRange(list.ToArray());

            foreach (var prd in list)
            {
                RanchDetailEntity entity = new RanchDetailEntity
                {
                    id = prd.id,
                    price = prd.price,
                    ingredients = prd.name,
                    description = prd.description,
                    upc = prd.identifier,
                    category = categoryList.departments.FirstOrDefault(p => p.id == prd.department_id[0])?.name,
                    net_weight = DateTime.Today.ToString("yyyy-MM-dd")
                };
                detailList.Add(entity);
            };
            Logger.Info("===》数据抓取完成");

        }

        private void ImportData(List<RanchDetailEntity> list)
        {  
            var data = new StringBuilder("id,name,category,description,price,upc" + Environment.NewLine);
            foreach (var item in list)
            {
                data.AppendLine($"{item.id},{item.name},{item.category},{item.description},{item.price},{item.upc}");
            }
            if (System.IO.File.Exists("ranch99.csv"))
            {
                System.IO.File.Delete("ranch99.csv");
            }
            System.IO.File.AppendAllText("ranch99.csv", data.ToString());
            Logger.Info("ranch99导出完成");
        }
        private RanchCategoryResult GetCategory()
        {
            RanchCategoryResult result = new RanchCategoryResult();
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"{apiService}&department_id_cascade=true&include_departments=true&include_offered_together=true&limit=0&render_id=1560477405201&store_id=3122&token={token}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchCategoryResult>(data);
            }
            return result;
        }

        private RanchProductResult GetProductList(int skip, int limit, string fields)
        {
            RanchProductResult result = new RanchProductResult();
            HttpClient client = new HttpClient();
            //var res = client.GetAsync($"{apiService}&department_id={department_id}&department_id_cascade=true&skip={skip}&fields={fields}&include_offered_together=true&limit={limit}&popularity_sort=asc&render_id=1560477405201&sort=popularity&store_id=3122&token={token}").Result;
            var res = client.GetAsync($"{apiService}&department_id_cascade=true&skip={skip}&fields={fields}&include_offered_together=true&limit={limit}&popularity_sort=asc&render_id=1560477405201&sort=popularity&store_id={store_id}&token={token}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchProductResult>(data);
            }
            return result;
        }
    }
}
